import moment from 'moment';
import EditPage from './edit';
import { Popconfirm, message, Button } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { renderText } from '@/utils/render';
import { TablePro, Review } from '@/components';
import getArticleList from '@/service/article/list';
import deleteService from '@/service/article/del';
import React, { useRef, useCallback } from 'react';

import styles from './styles.less';

const Article = () => {
  const tabRef = useRef<Function>();

  const onRefresh = useCallback(() => {
    tabRef.current?.();
  },[]);

  const onDelete = useCallback(async (record: any) => {
    const loadingClose = message.loading('删除中..')
    try {
      await deleteService(record);
      message.success('删除成功')
      onRefresh();
    } catch (e) {
      message.error('删除失败')
    }
    loadingClose();
  },[]);

  const columns = [
    {
      width: '120px',
      title: '预览图',
      dataIndex: 'banner',
      render: (url: string) => {
        return (
          <Review imgUrl={url}>
            <img
              src={url}
              alt="小图"
              className={styles.review_image}
            />
          </Review>
        );
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
      render: renderText
    },
    {
      title: '简略内容',
      dataIndex: 'simpleContent',
      render: renderText
    },
    {
      title: '创建时间',
      dataIndex: 'createdTime',
      render: (date: any) => (
        moment(date * 1000).format('YYYY-MM-DD HH:mm:ss')
      ),
    },
    {
      width: '200px',
      title: '操作',
      render: (record: any) => {
        return (
          <span className={styles.actions}>
            <EditPage
              data={record}
              onSuccess={onRefresh}
              children={ <a>编辑</a>}
            />
            <Popconfirm
              title="确定要删除吗?"
              onConfirm={() => onDelete(record)}
            >
              <a>删除</a>
            </Popconfirm>
          </span>
        );
      },
    },
  ];

  return (
    <>
      <div className={styles.header}>
        <EditPage onSuccess={onRefresh}>
          <Button type="primary" icon={<PlusOutlined />}>新建文章</Button>
        </EditPage>
      </div>
      <TablePro
        columns={columns}
        service={getArticleList}
        onLoad={cb => tabRef.current = cb}
      />
    </>
  );
};

export default Article;
